package sk.sodik.atomFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sk.sodik.atomFilter.feeds.EMF;
import sk.sodik.atomFilter.feeds.Feed;
import sk.sodik.atomFilter.feeds.FeedFilter;
import sk.sodik.atomFilter.feeds.FeedFilterId;

public class FeedServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(FeedServlet.class
			.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String path = req.getPathInfo();
		PrintWriter writer = resp.getWriter();
		// writer.println("Hello, nothing yet !!\n" + path);

		FeedFilterId id = parse(path);
		if (id == null) {
			error(req, resp, "Error parsing: " + path);
			return;
		}
		// writer.println("UserId:" + id.userId);
		// writer.println("Name:" + id.name);
		log.fine("Feed " + id.name + " from " + id.userId);

		FeedFilter feedFilter = EMF.load(id);
		if (feedFilter == null) {
			error(req, resp, "Feed filter not found: " + id);
			return;
		}

		Feed feed = new Feed(feedFilter.url);
		if (!feed.download()) {
			error(req, resp, "Error downloading: " + feedFilter.url);
			return;
		}

		log.fine("Feed downloaded from " + feedFilter.url);

		if (!feed.filter(feedFilter.filter)) {
			error(req, resp, "Error filtering: " + feedFilter.filter);
			return;
		}

		resp.setContentType("text/xml");
		feed.print(writer);

		log.fine("Feed returned!");
	}

	private void error(HttpServletRequest req, HttpServletResponse resp,
			String string) throws IOException {
		resp.setContentType("text/plain");
		PrintWriter writer = resp.getWriter();
		writer.print(string);
		log.severe(string);
	}

	private FeedFilterId parse(String path) {
		if (path == null || path.length() < 2) {
			return null;
		}
		path = path.substring(1);
		int i = path.indexOf('/');
		if (i < 0) {
			return null;
		}
		path = FeedFilterId.urlDecode(path);
		return new FeedFilterId(path);
	}

}
